<template>
  <div class="container-xl">
    <div class="row bg-white header borshow">
      <header class="col" :style="{ padding: '48px' }">
        <div class="row">
          <div class="col">
            <div class="div2">{{ getquestionbankbyid.name }}</div>
          </div>
          <div v-if="user" class="copy">
            <el-button @click="click()">
              <el-icon :size="14">
                <DocumentCopy />
              </el-icon>&nbsp;复制为我的题单
            </el-button>
          </div>
        </div>

        <el-divider :style="{ margin: '24px auto' }"></el-divider>
        <div class="div1">题目数量：{{ getquestionbankbyid.questionquestionbank?.length }}</div>
        <div class="div1">
          涵盖题目知识点：
          <el-button class="mb-1" type="primary" plain size="small" v-for="(vo, key) in label" :key="key"
            v-text="vo"></el-button>
        </div>

        <div class="div3">
          <span>模式选择：</span>
          <span class="span1">
            <el-tooltip placement="top">
              <template #content>
                常用的练习模式，非编程题可以直接看到答案
                <br />编程题可单独提交代码查看结果
              </template>
              <span @click="testclick(0)" :class="!istest ? 'span2' : ''">练习模式</span>
            </el-tooltip>
            <el-tooltip placement="top">
              <template #content>题单将作为试卷整体提交，提交后会统一显示每道题是否正确</template>
              <span @click="testclick(1)" :class="istest ? 'span2' : ''">评测模式</span>
            </el-tooltip>
          </span>
          <el-button @click="toquestion(istest)" :style="{ fintSize: '18px' }" type="primary">{{ !istest ? "进入练习" :
        "进入测评"
            }}</el-button>
        </div>
      </header>
    </div>
    <div class="row min-height bg-white borshow">
      <div class="col m-p-6">
        <table class="table table-borderless table-hover table-striped">
          <thead class="border-bottom thead">
            <tr>
              <td width="184" class="m-pl-6 m-border-2">题号</td>
              <td width="184">题型</td>
              <td scope="col">题目</td>
              <td width="368" class="m-border-2 m-pr-6">知识点</td>
            </tr>
          </thead>
          <tbody>
            <router-link v-for="(v, k) in question" :key="k" :to="istest
        ? `/test/${route.params.ID}/question/${k}`
        : `/question/${v?.ID}?questionbankid=${route.params.ID}`
        " custom v-slot="{ navigate }">
              <tr @click="navigate" class="m-t-l-28">
                <td class="text-x m-pl-6 m-border-2" v-text="v?.ID"></td>
                <td class="text-x" v-text="v?.type"></td>
                <td class="text-x" v-text="v?.name"></td>
                <td class="m-border-2 m-pr-6">
                  <div class="question-label">
                    <el-button type="primary" plain size="small" v-for="(vo, key) in v?.questionlabel"
                      :key="`${k}-${key}`" v-text="getlabel.find(e => e.ID === vo.labelid)?.name"></el-button>
                  </div>

                </td>
              </tr>
            </router-link>
          </tbody>
        </table>
        <div class="text-center" v-if="!question?.length">目前没有添加题目</div>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" title="复制" width="580px">
      <div>
        <el-input v-model="data.name">
          <template #prepend>编辑题单名称</template>
        </el-input>
      </div>
      <div>
        <h5 :style="{
        fontSize: '18px',
        fontWeight: 700,
        marginTop: '24px',
      }">请在下方选择需要复制的题单题目</h5>
      </div>
      <div :style="{}">
        <el-table ref="table" size="default" :data="getquestionbankbyid.questionquestionbank"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" />
          <el-table-column prop="ID" width="100" label="题号"></el-table-column>
          <el-table-column prop="question.name" label="题目"></el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submit">确定，并复制到我的题单</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { DocumentCopy } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElTable } from "element-plus";
import { uniq } from "underscore";
import { computed, onMounted, reactive, ref, watch } from 'vue';
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { asynccopyquestionbank, asyncgetquestionbank } from "../../../api";
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
const prop = defineProps<{ ID?: number }>()

const getquestionbankbyid = reactive<Studycodemodel.Iquestionbank>({ usertype: 'public', questionquestionbank: [] })
const dialogVisible = ref(false)
const data = reactive<Studycodemodel.Iquestionbank>({ usertype: 'public', questionquestionbank: [] })
onMounted(() => {
  start()
})

const route = useRoute()
const store = useStore(Storekey)
const getlabel = computed(() => {
  return store.state.label?.rows || []
})

const label = computed(() => {
  return uniq(question.value?.map(e => e?.questionlabel).map(e => e?.map(e => getlabel.value.find(t => t.ID === e.labelid)?.name)).flat().filter(e => e) || [])
})

const istest = computed(() => {
  return Boolean(Number(route.query.istest));
})

const question = computed(() => {
  return getquestionbankbyid.questionquestionbank?.map(
    ({ question }) => question
  )
  // .sort((a, b) => b?.ID - a?.ID)
})
const user = computed(() => {
  return store.state.user
})

watch(() => prop.ID, (v) => {
  if (v) start()
})
const router = useRouter()

async function start() {
  if (prop.ID) {
    try {
      const obj = await asyncgetquestionbank({ ID: prop.ID });
      Object.assign(getquestionbankbyid, obj)

    } catch (e) {
      ElMessage.error(e)
    }
  }
}

function testclick(t: number) {
  router.push({
    name: "题库列表",
    params: { ID: route.params.ID },
    query: {
      istest: t,
    },
  });
}

function toquestion(t: boolean) {
  if (!user.value) {
    return ElMessage.error('请登录')
  }
  if (!question.value?.length) {
    ElMessage.error("此题单没有题目");
    return;
  }
  if (t) {
    ElMessageBox.confirm("确定开始进行测评", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
    }).then((e) => {
      router.push(`/test/${route.params.ID}/question/0`);
    });
  } else {
    router.push({
      name: "题目",
      params: { ID: question.value[0]?.ID },
      query: { questionbankid: route.params.ID },
    });
  }
}

const table = ref<typeof ElTable>()

function click() {
  if (!store.state.user) {
    return;
  }
  Object.assign(data, JSON.parse(JSON.stringify(getquestionbankbyid)))
  dialogVisible.value = true;
  setTimeout(() => {
    if (table.value)
      table.value.toggleAllSelection();
  }, 100);
}

async function submit() {
  if (!store.state.user) {
    return;
  }
  data.userid = store.state.user.ID;
  data.ID = undefined;
  await asynccopyquestionbank(data);
  dialogVisible.value = false;
  ElMessage.success("复制成功");
}

function handleSelectionChange(selection: Studycodemodel.Iquestionquestionbank[]) {
  data.questionquestionbank = selection;
}

</script>

<style scoped>
.header {
  margin-top: 24px;
  margin-bottom: 24px;
  height: 415px;
  border-radius: 2px;
}

.div2 {
  color: #434343;
  font-weight: bold;
  font-size: 32px;
  font-style: normal;
}

.div1 {
  margin-top: 24px;
}

.text-x {
  cursor: pointer;
}

.div3 {
  margin-top: 48px;
  line-height: 42px;
  height: 48px;
  padding-top: 3px;
  padding-bottom: 3px;
}

.span1 {
  display: inline-block;
  width: 208px;
  height: 42px;
  background: #f5f5f5;
  border-radius: 24px;
  text-align: center;
  margin-left: 35px;
  margin-right: 90px;
}

.span1 span {
  display: inline-block;
  width: 104px;
  height: 42px;
  border-radius: 24px;
  font-weight: bold;
  transition: all 0.3s;
  cursor: pointer;
}

.span2 {
  background: var(--color-cheng);
  color: #ffffff;
}

.el-tag {
  margin: 5px;
}

.m-pl-6 {
  padding-left: 24px !important;
}

.m-pr-6 {
  padding-right: 24px !important;
}

.copy {
  display: inline-block;
  cursor: pointer;
  text-align: center;
  font-size: 18px;
  font-weight: 400;
  width: 200px;
  height: 48px;
  line-height: 48px;
  border-radius: 2px;
}

.copy:hover {
  color: var(--color-cheng);
}

.question-label {
  overflow: hidden;
  max-width: 368px;
  max-height: 48px;
}
</style>